package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	// `json:"id"` 为结构体标签,指定json中序列化的属性名
	ID     int    `json:"id"`
	Gender string `json:"gender"`
	// 私有属性不能被json访问
	Name string `json:"name"`
	Sno  string `json:"sno"`
}

type Class struct {
	Name     string    `json:"name"`
	Students []Student `json:"students"`
}

func main() {
	//var s1 = Student{
	//	ID:     1,
	//	Gender: "男",
	//	Name:   "张三",
	//	Sno:    "001",
	//}
	//
	//fmt.Printf("%#v\n", s1)
	//
	//// 对象转json字符串
	//jsonByte, _ := json.Marshal(s1)
	//jsonStr := string(jsonByte)
	//fmt.Println(jsonStr)
	//
	//// json字符串转对象
	////var str = `{"ID":1111,"Gender":"男","Name":"张三2","Sno":"0011"}`
	//var str = `{"id":1,"gender":"男","name":"张三","sno":"001"}`
	//var s2 Student
	//err2 := json.Unmarshal([]byte(str), &s2)
	//if err2 != nil {
	//	fmt.Println("json字符串转对象失败")
	//}
	//fmt.Printf("%#v\n", s2)

	var class = Class{
		Name: "1班",
		Students: []Student{
			{ID: 1, Gender: "男", Name: "张三", Sno: "001"},
			{ID: 2, Gender: "女", Name: "李四", Sno: "002"},
		},
	}
	jsonByte, _ := json.Marshal(class)
	jsonStr := string(jsonByte)
	fmt.Println("序列化json: ", jsonStr)

	var class2 Class
	err2 := json.Unmarshal([]byte(jsonStr), &class2)
	if err2 != nil {
		fmt.Println("json字符串转对象失败")
	}
	fmt.Printf("反序列化对象: %#v\n", class2)
}
